﻿using System.Data;
using System.Threading;
using System.Threading.Tasks;
using NetMicro.EventBus.Extensions;
using NetMicro.EventBus.Messages;
using NetMicro.EventBus.Persistences;

namespace NetMicro.EventBus.Policies
{
    public class EventErrorSendDeadLetter : IEventErrorSendDeadLetter
    {
        private IDeadLetterMessageStorage DeadLetterMessageStorage { get; }

        private IMessageSerializer MessageSerializer { get; }
        public EventErrorSendDeadLetter(IDeadLetterMessageStorage deadLetterMessageStorage, IMessageSerializer messageSerializer)
        {
            DeadLetterMessageStorage = deadLetterMessageStorage;
            MessageSerializer = messageSerializer;
        }
        public async Task OnSendDeadLetterAsync(MessageTransfer messageTransfer, IDbTransaction transaction = null, CancellationToken cancellationToken = default)
        {
            MessageStorageTransfer deadLetterMessage = MessageSerializer.ConvertMessageStorageTransfer(messageTransfer);
            await DeadLetterMessageStorage.SaveAsync(deadLetterMessage, transaction);
        }
    }
}
